<template>
  <view class="profile-edit-container">
    <!-- 页面标题 -->
    <view class="page-header">
      <view class="header-left" @click="goBack">
        <text class="iconfont icon-back"></text>
      </view>
      <view class="header-title">编辑资料</view>
      <view class="header-right"></view>
    </view>
    
    <!-- 头像编辑 -->
    <view class="avatar-section">
      <view class="avatar-wrapper" @click="changeAvatar">
        <image class="user-avatar" :src="userInfo.avatar" mode="aspectFill"></image>
        <view class="avatar-edit-icon">
          <text class="iconfont icon-camera"></text>
        </view>
      </view>
      <text class="avatar-tip">点击更换头像</text>
    </view>
    
    <!-- 表单区域 -->
    <view class="form-section">
      <view class="form-item">
        <text class="form-label">昵称</text>
        <input 
          class="form-input" 
          type="text" 
          v-model="userInfo.nickname" 
          placeholder="请输入昵称"
          maxlength="20"
        />
      </view>
      
      <view class="form-item">
        <text class="form-label">个性签名</text>
        <textarea 
          class="form-textarea" 
          v-model="userInfo.bio" 
          placeholder="介绍一下自己吧"
          maxlength="100"
        />
        <text class="textarea-counter">{{userInfo.bio ? userInfo.bio.length : 0}}/100</text>
      </view>
      
      <view class="form-item">
        <text class="form-label">性别</text>
        <picker 
          class="form-picker" 
          :range="genderOptions" 
          range-key="label"
          :value="genderIndex" 
          @change="onGenderChange"
        >
          <view class="picker-value">
            <text>{{genderOptions[genderIndex].label}}</text>
            <text class="iconfont icon-right"></text>
          </view>
        </picker>
      </view>
      
      <view class="form-item">
        <text class="form-label">地区</text>
        <picker 
          class="form-picker" 
          mode="region" 
          :value="regionArray" 
          @change="onRegionChange"
        >
          <view class="picker-value">
            <text>{{regionArray.join(' ') || '请选择地区'}}</text>
            <text class="iconfont icon-right"></text>
          </view>
        </picker>
      </view>
    </view>
    
    <!-- 底部保存按钮 -->
    <view class="bottom-save-btn" @click="saveProfile">
      <text>保存</text>
    </view>
  </view>
</template>

<script>
import api from '@/utils/api.js';

export default {
  data() {
    return {
      // 用户信息
      userInfo: {
        userId: '',
        nickname: '',
        avatar: '/static/images/default-avatar.png',
        bio: '',
        gender: 0, // 0-未设置，1-男，2-女
        region: ''
      },
      
      // 性别选项
      genderOptions: [
        { value: 0, label: '未设置' },
        { value: 1, label: '男' },
        { value: 2, label: '女' }
      ],
      
      // 当前选中的性别索引
      genderIndex: 0,
      
      // 地区数组
      regionArray: ['', '', ''],
      
      // 原始用户信息（用于检测是否有修改）
      originalUserInfo: null
    };
  },
  
  onLoad() {
    // 加载用户信息
    this.loadUserInfo();
  },
  
  methods: {
    /**
     * 加载用户信息
     */
    async loadUserInfo() {
      try {
        uni.showLoading({
          title: '加载中...',
          mask: true
        });
        
        const res = await api.user.getUserInfo();
        
        if (res.code === 200 && res.data) {
          // 更新用户信息
          this.userInfo = {
            userId: res.data.id || '',
            nickname: res.data.nickname || '',
            avatar: res.data.avatar || '/static/images/default-avatar.png',
            bio: res.data.bio || '',
            gender: res.data.gender || 0,
            region: res.data.region || ''
          };
          
          // 设置性别索引
          this.genderIndex = this.genderOptions.findIndex(item => item.value === this.userInfo.gender);
          if (this.genderIndex === -1) this.genderIndex = 0;
          
          // 设置地区数组
          if (this.userInfo.region) {
            this.regionArray = this.userInfo.region.split(' ');
            // 确保数组长度为3
            while (this.regionArray.length < 3) {
              this.regionArray.push('');
            }
          }
          
          // 保存原始信息（用于检测是否有修改）
          this.originalUserInfo = JSON.parse(JSON.stringify(this.userInfo));
        } else {
          uni.showToast({
            title: res.message || '获取用户信息失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('加载用户信息失败', error);
        uni.showToast({
          title: '加载用户信息失败',
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    },
    
    /**
     * 更换头像
     */
    changeAvatar() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0];
          
          // 显示上传中提示
          uni.showLoading({
            title: '上传中...',
            mask: true
          });
          // 上传头像
          api.image.uploadImage(tempFilePath, (progress) => {
            console.log('上传进度', progress);
          }).then(res => {
            if (res.code === 200 && res.data) {
              // 更新头像
              this.userInfo.avatar = res.data.imageUrl;
              
              uni.showToast({
                title: '头像上传成功',
                icon: 'success'
              });
            } else {
              uni.showToast({
                title: res.message || '头像上传失败',
                icon: 'none'
              });
            }
          }).catch(err => {
            console.error('头像上传失败', err);
            uni.showToast({
              title: '头像上传失败',
              icon: 'none'
            });
          }).finally(() => {
            uni.hideLoading();
          });
        }
      });
    },
    
    /**
     * 性别选择变化
     */
    onGenderChange(e) {
      const index = e.detail.value;
      this.genderIndex = index;
      this.userInfo.gender = this.genderOptions[index].value;
    },
    
    /**
     * 地区选择变化
     */
    onRegionChange(e) {
      this.regionArray = e.detail.value;
      this.userInfo.region = this.regionArray.join(' ');
    },
    
    /**
     * 保存个人资料
     */
    async saveProfile() {
      // 验证昵称
      if (!this.userInfo.nickname.trim()) {
        uni.showToast({
          title: '昵称不能为空',
          icon: 'none'
        });
        return;
      }
      
      // 检查是否有修改
      if (JSON.stringify(this.userInfo) === JSON.stringify(this.originalUserInfo)) {
        uni.navigateBack();
        return;
      }
      
      try {
        uni.showLoading({
          title: '保存中...',
          mask: true
        });
        
        // 准备更新数据
        const updateData = {
          id: this.userInfo.userId,
          avatar:this.userInfo.avatar,
          nickname: this.userInfo.nickname,
          bio: this.userInfo.bio,
          gender: this.userInfo.gender,
          region: this.userInfo.region
        };
        
        const res = await api.user.updateUserInfo(updateData);
        
        if (res.code === 200) {
          uni.showToast({
            title: '保存成功',
            icon: 'success'
          });
          
          // 返回上一页
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } else {
          uni.showToast({
            title: res.message || '保存失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('保存个人资料失败', error);
        uni.showToast({
          title: '保存失败，请重试',
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    },
    
    /**
     * 返回上一页
     */
    goBack() {
      // 检查是否有修改
      if (JSON.stringify(this.userInfo) !== JSON.stringify(this.originalUserInfo)) {
        uni.showModal({
          title: '提示',
          content: '您的资料已修改，是否保存？',
          cancelText: '不保存',
          confirmText: '保存',
          success: (res) => {
            if (res.confirm) {
              this.saveProfile();
            } else {
              uni.navigateBack();
            }
          }
        });
      } else {
        uni.navigateBack();
      }
    }
  }
};
</script>

<style lang="scss">
@import '@/static/styles/global.scss';

.profile-edit-container {
  min-height: 100vh;
  background-color: $background-color;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  background-color: #FFFFFF;
  position: sticky;
  top: 0;
  z-index: 100;
  height: 88rpx;
  
  .header-left {
    min-width: 120rpx;
    height: 100%;
    display: flex;
    align-items: center;
  }
  
  .header-left {
    justify-content: flex-start;
  }
  
  .header-right {
    min-width: 120rpx;
  }
  
  .header-title {
    flex: 1;
    text-align: center;
    font-size: 32rpx;
    font-weight: bold;
    color: $text-color-primary;
  }
  
  .icon-back {
    font-size: 36rpx;
    color: $text-color-primary;
    padding: 20rpx;
  }
}

// 底部保存按钮样式
.bottom-save-btn {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background-color: $primary-color;
  color: #FFFFFF;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
  font-weight: bold;
  z-index: 100;
  
  // 适配底部安全区
  padding-bottom: env(safe-area-inset-bottom);
  
  // 点击效果
  &:active {
    opacity: 0.9;
  }
}

// 为底部按钮留出空间
.form-section {
  margin-bottom: calc(100rpx + env(safe-area-inset-bottom));
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40rpx 0;
  background-color: #FFFFFF;
  margin-bottom: 20rpx;
  
  .avatar-wrapper {
    position: relative;
    width: 160rpx;
    height: 160rpx;
    border-radius: $border-radius-circle;
    overflow: hidden;
    margin-bottom: 20rpx;
  }
  
  .user-avatar {
    width: 100%;
    height: 100%;
  }
  
  .avatar-edit-icon {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 50rpx;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    
    .icon-camera {
      font-size: 28rpx;
      color: #FFFFFF;
    }
  }
  
  .avatar-tip {
    font-size: 24rpx;
    color: $text-color-secondary;
  }
}

.form-section {
  background-color: #FFFFFF;
  padding: 0 30rpx;
  
  .form-item {
    position: relative;
    padding: 30rpx 0;
    border-bottom: 1rpx solid $border-color-light;
    
    &:last-child {
      border-bottom: none;
    }
  }
  
  .form-label {
    font-size: 28rpx;
    color: $text-color-primary;
    margin-bottom: 20rpx;
    display: block;
  }
  
  .form-input {
    font-size: 28rpx;
    color: $text-color-primary;
    width: 100%;
    height: 60rpx;
  }
  
  .form-textarea {
    font-size: 28rpx;
    color: $text-color-primary;
    width: 100%;
    height: 160rpx;
    line-height: 1.5;
  }
  
  .textarea-counter {
    position: absolute;
    right: 0;
    bottom: 30rpx;
    font-size: 24rpx;
    color: $text-color-secondary;
  }
  
  .form-picker {
    width: 100%;
  }
  
  .picker-value {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 28rpx;
    color: $text-color-primary;
    height: 60rpx;
    
    .icon-right {
      font-size: 24rpx;
      color: $text-color-secondary;
    }
  }
}
</style>
